import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
    //修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
const routes = [{
        path: "/",
        redirect: "/home"
    }, {
        path: '/home',
        name: 'home',
        component: () =>
            import ("../components/index.vue"),
        meta: {
            title: "首页"
        }
    },
    {
        path: '/about',
        name: 'About',
        component: () =>
            import ('../views/About.vue'),
        meta: {
            title: "about"
        }
    },
    //详情
    {
        path: '/detail',
        name: 'detail',
        component: () =>
            import ("../components/detail.vue"),
        meta: {
            title: "详情"
        },
    },
    //列表
    {
        path: '/goodslist',
        name: 'goodslist',
        component: () =>
            import ("../components/goodslist.vue"),
        meta: {
            title: "商品列表"
        }
    },
    {
        path: '/allgoodslist',
        name: 'allgoodslist',
        component: () =>
            import ("../components/allgoods.vue"),
        meta: {
            title: "所有商品"
        }
    },
    {
        path: "/userReg",
        name: "userReg",
        component: () =>
            import ("../components/userReg.vue"),
        meta: {
            title: "注册"
        }
    },
    {
        path: "/sign",
        name: "sign",
        component: () =>
            import ("../components/sign.vue"),
        meta: {
            title: "登录"
        },
        beforeEnter: ((to, from, next) => {
            to.query.url = from.path;
            next();
        }),
    },
    //购物车 
    {
        path: "/cart",
        name: "cart",
        component: () =>
            import ("../views/cart.vue"),
        meta: {
            title: "购物车"
        }
    },

]

const router = new VueRouter({
    routes
})
router.beforeEach((to, from, next) => {
    const pwd = sessionStorage.getItem("pwd");
    document.title = to.meta.title;
    if (to.path == "/cart") {
        if (pwd != "已经登陆过了") {
            alert("请先登录!")
            return next("/sign")
        };
        next();
    } else {
        next();
    }
});

export default router